package com.whfc.emp.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.PageData;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.result.ResultUtil;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.PageUtil;
import com.whfc.emp.dao.AppExamAnswerRecordMapper;
import com.whfc.emp.dao.AppExamPaperMapper;
import com.whfc.emp.dao.AppExamRecordMapper;
import com.whfc.emp.dao.AppTrainingQuestionMapper;
import com.whfc.emp.dto.AppExamPaperDTO;
import com.whfc.emp.dto.AppExamRecordDTO;
import com.whfc.emp.dto.AppTrainingQuestionsDTO;
import com.whfc.emp.dto.AppTrainingQuestionsOptionsDTO;
import com.whfc.emp.entity.*;
import com.whfc.emp.param.AppExamRecordAddParam;
import com.whfc.emp.param.AppExamRecordListParam;
import com.whfc.emp.service.AppExamRecordService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClasssName AppTrainServiceImpl
 * @Description 人员管理-培训
 * @Author hw
 * @Date 2020/11/26 16:18
 * @Version 1.0
 */
@DubboService(interfaceClass = AppExamRecordService.class, version = "1.0.0", timeout = 5000)
public class AppExamRecordServiceImpl implements AppExamRecordService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppExamRecordMapper appExamRecordMapper;
    @Autowired
    private AppExamAnswerRecordMapper appExamAnswerRecordMapper;
    @Autowired
    private AppExamPaperMapper appExamPaperMapper;
    @Autowired
    private AppTrainingQuestionMapper appTrainingQuestionMapper;


    @Override
    public PageData<AppExamRecordDTO> list(AppExamRecordListParam request) throws BizException {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());

        List<AppExamRecordDTO> list = appExamRecordMapper.selectByParam(request);
        List<AppExamPaperDTO> list1 = appExamPaperMapper.selectByIds(list.stream().map(AppExamRecordDTO -> AppExamRecordDTO.getExamPaperId()).collect(Collectors.toList()));
        list.forEach(item -> {
            item.setExamPaper(list1.stream().filter(item1 -> item1.getId().equals(item.getExamPaperId())).findFirst().orElse(null));
        });
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    @Transactional
    public Result add(AppExamRecordAddParam request) throws BizException {
        AppExamPaper appExamPaper = appExamPaperMapper.selectByPrimaryKey(request.getExamPaperId());
        if (appExamPaper == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "未找到该考试或培训.");
        }

        //保存考试记录
        AppExamRecord appExamRecord = appExamRecordMapper.selectByUserIdAndExamPaperId(request.getUserId(), request.getExamPaperId());
        if (appExamRecord == null) {
            appExamRecord = new AppExamRecord();
            appExamRecord.setUserId(request.getUserId());
            appExamRecord.setExamPaperId(request.getExamPaperId());
            appExamRecord.setStartTime(DateUtil.getTime(new Date()));
            appExamRecordMapper.insert(appExamRecord);
        }
        // 保存答题记录
        AppExamAnswerRecord appExamAnswerRecord = appExamAnswerRecordMapper.selectByPaperIdAndUserId(request.getExamPaperId(), request.getUserId(), request.getQuestionId());
        if (appExamAnswerRecord == null) {
            appExamAnswerRecord = new AppExamAnswerRecord();
            appExamAnswerRecord.setUserId(request.getUserId());
            appExamAnswerRecord.setExamPaperId(request.getExamPaperId());
            appExamAnswerRecord.setQuestionId(request.getQuestionId());
            appExamAnswerRecord.setSelectedAnswer(request.getSelectedAnswer());
            appExamAnswerRecord.setCreateTime(DateUtil.getTime(new Date()));
            getAnswerResult(request, appExamAnswerRecord);

            appExamAnswerRecordMapper.insert(appExamAnswerRecord);
        } else {
            appExamAnswerRecord.setSelectedAnswer(request.getSelectedAnswer());
            getAnswerResult(request, appExamAnswerRecord);
            appExamAnswerRecordMapper.updateByPrimaryKey(appExamAnswerRecord);
        }
        Integer count = appExamAnswerRecordMapper.selectCount(request.getExamPaperId(), request.getUserId());
        if (appExamPaper.getQty() == count) {
            Integer sumCore = appExamAnswerRecordMapper.getSumCore(request.getExamPaperId(), request.getUserId());
            if (sumCore != null) {
                appExamRecord.setTotalScore(sumCore);
                appExamRecord.setState(1);
                appExamRecordMapper.updateByPrimaryKey(appExamRecord);
            }
        }

        return ResultUtil.success(appExamRecord);
    }

    /**
     * 获取答题结果
     *
     * @param request
     * @param appExamAnswerRecord
     */
    private void getAnswerResult(AppExamRecordAddParam request, AppExamAnswerRecord appExamAnswerRecord) {
        List<AppTrainingQuestionsOptionsDTO> appTrainingQuestion = appTrainingQuestionMapper.selectOptionsByQuestionId(request.getQuestionId());
        if (CollUtil.isNotEmpty(appTrainingQuestion)) {
            String correctAnswers = appTrainingQuestion.stream()
                    .filter(item -> item.getIsCorrect() == 1)
                    .map(AppTrainingQuestionsOptionsDTO::getOptionLabel)
                    .collect(Collectors.joining(","));
            if (correctAnswers.equals(request.getSelectedAnswer())) {
                appExamAnswerRecord.setIsCorrect(1);
                appExamAnswerRecord.setScoreAwarded(5);
            }
        }
        appExamAnswerRecordMapper.updateByPrimaryKey(appExamAnswerRecord);
    }

    @Override
    public void del(Integer id) throws BizException {

    }

    @Override
    public PageData<AppExamRecordDTO> getExamRecordList(AppExamRecordListParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<AppExamRecordDTO> list = appExamRecordMapper.selectByParam(param);
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }
}
